﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FieldUpdater.Classes;

namespace FieldUpdater.SharePointRoot.Template.Layouts
{
    public partial class ManageFieldAssociations : System.Web.UI.Page
    {
        private ListDAL m_ListDAL = null;
        public ListDAL ListDAL
        {
            get
            {
                if (m_ListDAL == null)
                    m_ListDAL = new ListDAL(new Guid(Request["List"]));
                return m_ListDAL;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            cmdAdd.Click += new EventHandler(cmdAdd_Click);
            cmdUpdate.Click += new EventHandler(cmdAdd_Click);
            cmdCancel.Click += new EventHandler(cmdCancel_Click);
            cmdDelete.Click += new EventHandler(cmdDelete_Click);
            gvDefinitions.RowEditing += new GridViewEditEventHandler(gvDefinitions_RowEditing);

            if (!IsPostBack)
            {
                // Fill Connection Type drop down list
                var names = Enum.GetNames(typeof(ConnectionTypes));

                foreach (var name in names)
                    ddlConnectionType.Items.Add(new ListItem
                        {
                            Text = FieldAssociation.GetConnectionTypeString(name),
                            Value = name
                        });
            }
        }

        void cmdDelete_Click(object sender, EventArgs e)
        {
            var definitions = this.ListDAL.GetDefinitions();
            var rowIndex = int.Parse(hidEditIndex.Value);
            definitions.Associations.RemoveAt(rowIndex);
            this.ListDAL.SaveDefinitions(definitions);

            SetMode(PageMode.New);            
        }

        void cmdCancel_Click(object sender, EventArgs e)
        {
            SetMode(PageMode.New);
        }

        void gvDefinitions_RowEditing(object sender, GridViewEditEventArgs e)
        {
            var rowIndex = e.NewEditIndex;

            var definitions = ListDAL.GetDefinitions();
            var definition = definitions.Associations[rowIndex];

            txtSource.Text = definition.ParentFieldName;
            var connectionTypeStr = definition.ConnectionType.ToString();
            
            if (definition.ConnectionType == ConnectionTypes.Oracle)
            {
                if (definitions.OracleConnections.ContainsKey(definition.ParentFieldName))
                {
                    var oracleDefinition = definitions.OracleConnections[definition.ParentFieldName];
                    txtConnectionString.Text = oracleDefinition.ConnectionString;
                    txtSourceColumn.Text = oracleDefinition.SourceColumn;
                    txtTableName.Text = oracleDefinition.TableName;
                }
                txtTargetColumns.Text = (from def in definitions.Associations
                                         where def.ParentFieldName == definition.ParentFieldName
                                         select def.ChildFieldName + "=" + def.ConnectingFieldName).Combine(';');
            }
            else
            {
                txtDestination.Text = definition.ChildFieldName;
                txtConnection.Text = definition.ConnectingFieldName;
            }

            for (int itemIndex = 0; itemIndex < ddlConnectionType.Items.Count; itemIndex++)
                if (ddlConnectionType.Items[itemIndex].Value == connectionTypeStr)
                    ddlConnectionType.SelectedIndex = itemIndex;

            trConnectionField.Style[HtmlTextWriterStyle.Display] =
                (definition.ConnectionType == ConnectionTypes.SharePointLookup ? "block" : "none");

            trTargetField.Style[HtmlTextWriterStyle.Display] =
                (definition.ConnectionType != ConnectionTypes.Oracle ? "block" : "none");

            trOracleConnectionSettings.Style[HtmlTextWriterStyle.Display] =
                (definition.ConnectionType == ConnectionTypes.Oracle ? "block" : "none");

            SetMode(PageMode.Edit, rowIndex.ToString());
        }

        private void SetMode(PageMode pageMode)
        {
            SetMode(pageMode, "-1");
        }
        private void SetMode(PageMode pageMode, string index)
        {
            var editMode = (pageMode == PageMode.Edit);
            cmdUpdate.Visible = editMode;
            cmdDelete.Visible = editMode;
            cmdCancel.Visible = editMode;
            hidEditIndex.Value = index;
        }

        void cmdAdd_Click(object sender, EventArgs e)
        {
            var isEditMode = (((Button)sender).CommandName == "Update");

            var definitions = this.ListDAL.GetDefinitions();
            var editIndex = int.Parse(hidEditIndex.Value);

            var connectionType = (ConnectionTypes)Enum.Parse(typeof(ConnectionTypes), ddlConnectionType.SelectedValue);

            if (connectionType == ConnectionTypes.Oracle)
            {
                var parentFieldName = txtSource.Text;
                if (definitions.OracleConnections.ContainsKey(txtSource.Text))
                    definitions.OracleConnections.Remove(txtSource.Text);

                for (int deleteIndex = 0; deleteIndex < definitions.Associations.Count; deleteIndex++)
                    if (definitions.Associations[deleteIndex].ParentFieldName == parentFieldName)
                        definitions.Associations.RemoveAt(deleteIndex--);

                if (!string.IsNullOrEmpty(txtTargetColumns.Text))
                {
                    // Adding new oracle connection
                    definitions.OracleConnections.Add(txtSource.Text,
                        new OracleConnection
                        {
                            ColumnName = txtSource.Text,
                            ConnectionString = txtConnectionString.Text,
                            TableName = txtTableName.Text,
                            SourceColumn = txtSourceColumn.Text,
                            TargetColumns = txtTargetColumns.Text
                        });

                    // Adding field connections
                    definitions.Associations.AddRange(from str in txtTargetColumns.Text.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                                         select new FieldAssociation
                                         {
                                             ParentFieldName = parentFieldName,
                                             ConnectionType = ConnectionTypes.Oracle,
                                             ChildFieldName = str.Split('=')[0],
                                             ConnectingFieldName = str.Split('=')[1]
                                         });
                }
            }
            else if (isEditMode)
            {
                var definition = definitions.Associations[editIndex];
                definition.ParentFieldName = txtSource.Text;
                definition.ChildFieldName = txtDestination.Text;
                definition.ConnectingFieldName = txtConnection.Text;
                definition.ConnectionType = connectionType;
            }
            else
            {
                definitions.Associations.Add(new FieldAssociation
                {
                    ParentFieldName = txtSource.Text,
                    ChildFieldName = txtDestination.Text,
                    ConnectingFieldName = txtConnection.Text,
                    ConnectionType = connectionType
                });
            }

            this.ListDAL.SaveDefinitions(definitions);
            SetMode(PageMode.New);
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            gvDefinitions.DataSource = this.ListDAL.GetDefinitions().Associations;
            gvDefinitions.DataBind();
        }
    }
}